package cn.strive.eams.scrapRequire.service.impl;

import cn.strive.eams.application.mapper.ApplicationMapper;
import cn.strive.eams.application.pojo.entity.Application;
import cn.strive.eams.base.enmus.ApplicationStatusEnum;
import cn.strive.eams.room.pojo.entity.Room;
import cn.strive.eams.scrapRequire.mapper.ScrapRequireMapper;
import cn.strive.eams.scrapRequire.pojo.dto.ScrapRequireSaveParam;
import cn.strive.eams.scrapRequire.pojo.entity.ScrapRequire;
import cn.strive.eams.scrapRequire.service.ScrapRequireService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Slf4j
@Service
public class ScrapRequireServiceImpl implements ScrapRequireService {
    @Autowired
    ScrapRequireMapper scrapRequireMapper;
    @Autowired
    ApplicationMapper applicationMapper;
    @Override
    public void saveScrapRequireService(ScrapRequireSaveParam scrapRequireSaveParam) {
        log.debug("保存报废单业务，参数{}",scrapRequireSaveParam);
        ScrapRequire scrapRequire = new ScrapRequire();
        BeanUtils.copyProperties(scrapRequireSaveParam,scrapRequire);
        scrapRequire.setCreateTime(new Date());
        log.debug("报废单对象:{}",scrapRequire);
        scrapRequireMapper.insert(scrapRequire);

        Application application = new Application();
        BeanUtils.copyProperties(scrapRequireSaveParam,application);
        application.setApplyId(scrapRequire.getId());
        application.setApplyNumber(generateApplyNumber());
        application.setStatus(ApplicationStatusEnum.PENDING.getCode());
        application.setCreateTime(new Date());
        log.debug("application={}",application);
        applicationMapper.insert(application);

    }

    private String generateApplyNumber() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String currentDateStr = LocalDate.now().format(formatter);

        // 初始化四位数字部分，从0000开始
        int numberPart = 0;

        String applyNumber;
        do {
            String formattedNumber = String.format("%04d", numberPart);
            applyNumber = "APPLY" + currentDateStr + formattedNumber;

            // 检查是否有重复的昵称
            if (!isApplyNumberExists(applyNumber)) {
                break;
            }

            // 如果存在重复，则将数字部分增加10
            numberPart += 10;
        } while (true);

        return applyNumber;
    }

    private boolean isApplyNumberExists(String applyNumber) {
        return applicationMapper.existsByApplyNumber(applyNumber) > 0;
    }
}
